# api_utils.py - API工具函数
import requests

def generate_answer_with_rag(question, relevant_chunks, api_token, model_name, base_url):
    """使用RAG生成答案"""
    # 构建包含检索内容的提示
    if isinstance(relevant_chunks[0], dict):
        context_contents = [chunk['content'] for chunk in relevant_chunks if 'content' in chunk]
    else:
        context_contents = relevant_chunks
    
    context = "\n\n".join(context_contents)
    
    if len(context) > 4000:
        context = context[:4000] + "..."
    
    system_prompt = """你是一个仓颉编程语言专家。请根据提供的文档内容回答问题。

文档内容：
{context}

请基于以上文档内容，专业、准确地回答用户问题。如果文档中没有相关信息，请基于你的编程知识进行回答，但要说明这不是文档中的内容。"""

    prompt = system_prompt.format(context=context) + f"\n\n问题：{question}\n\n回答："

    headers = {'Authorization': f'Bearer {api_token}', 'Content-Type': 'application/json'}
    data = {
        "model": model_name,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 2000,
        "temperature": 0.7
    }

    try:
        response = requests.post(f"{base_url}chat/completions", headers=headers, json=data, timeout=60)
        if response.status_code == 200:
            result = response.json()
            answer = result['choices'][0]['message']['content']
            
            # 添加引用信息
            if len(context_contents) > 0 and "未找到" not in context_contents[0]:
                answer += f"\n\n📚 以上回答基于仓颉文档的相关内容。"
            
            return answer
        else:
            return f"❌ API错误: {response.status_code} - {response.text}"
    except Exception as e:
        return f"❌ 请求错误: {str(e)}"